<template>
  <div>
    <!-- Audios -->
    <audio id="audio_remote" autoplay="autoplay"></audio>
    <!-- 回铃音 -->
    <audio id="dialtone" muted src="/static/sounds/dialtone.wav"></audio>
    <!-- 处理监听只能打视频问题 -->
    <video v-show="false" class="video" id="remoteVideo" autoplay></video>
  </div>
</template>

<script>
import { webrtcList } from '@/api/webrtc'
import Webrtc2Sip from '@/utils/Webrtc2Sip'
import { mapGetters, mapState } from 'vuex'
import store from '@/store'

import Notify from './Notify'
export default {
  data() {
    return {
      notify: null, // 来电通知对象，用来关闭
      isAnswered: false, // 是否已接听
      webrtc2Sip: '', //手柄
      webrtc2SipVice: '', //手咪
    }
  },
  computed: {
    ...mapGetters([
      'localPhoneStatus',
      'localButtonStatus',
      'callFlag',
      'deviceStatusMap',
      'operatorCallTels',
    ]),
  },
  methods: {
    // sip栈事件 -- 来电等事件
    stackEvent(e, webrtc2Sip, acceptCallback, hangupCallback) {
      console.log('调用全局事件stackEvent', e.type, e.description)
      if (e.type === 'i_new_call') {
        console.log(
          '--------e.incomingName----------',
          e.incomingName,
          webrtc2Sip
        )
        console.log(this.callFlag)
        if (this.callFlag) {
          webrtc2Sip.sipAnswer()
          this.isAnswered = true
          store.commit('callFlagEvent', false)
        } else {
          this.incomingNotify(
            e.incomingName,
            webrtc2Sip,
            acceptCallback,
            hangupCallback
          )
        }
      }
    },
    // 会话事件 -- 挂断等
    sessionEvent(e, sessionType, webrtc2Sip) {
      console.log('sessionEvent', e.type, e.description)
      if (e.type === 'terminating' || e.type === 'terminated') {
        this.closeNotify()
        console.log('global terminated')
        store.commit('callFlagEvent', false)
      }
    },
    // 拒接或挂断
    handleReject(webrtc2Sip, hangupCallback) {
      this.handlePlayDialt('pause')
      if (hangupCallback) {
        hangupCallback(
          webrtc2Sip,
          this.notify,
          this.isAnswered ? 'hangup' : 'reject'
        )
        return
      }
      if (webrtc2Sip) webrtc2Sip.sipHangUp()
      this.closeNotify()
      store.commit('callFlagEvent', false)
    },
    // 接听
    handleAccept(webrtc2Sip, acceptCallback) {
      console.log('handleAnswer', webrtc2Sip)
      this.handlePlayDialt('pause')
      this.isAnswered = true
      if (acceptCallback) {
        acceptCallback(webrtc2Sip, this.notify)
      } else if (webrtc2Sip) {
        webrtc2Sip.sipAnswer()
      }
    },
    // 关闭来电显示
    closeNotify() {
      if (this.notify) this.notify.close()
      this.isAnswered = false
    },
    // 来电显示
    incomingNotify(incomingName, webrtc2Sip, acceptCallback, hangupCallback) {
      const h = this.$createElement
      // this.closeNotify()
      this.notify = this.$notify({
        position: 'bottom-right',
        duration: 0,
        showClose: false,
        customClass: 'ring-pop-up',
        dangerouslyUseHTMLString: true,
        message: h(Notify, {
          props: {
            webrtc2Sip: webrtc2Sip,
            answer: () => this.handleAccept(webrtc2Sip, acceptCallback),
            hangup: () => this.handleReject(webrtc2Sip, hangupCallback),
          },
        }),
      })
    },
    // 初始化
    initWebrtc() {
      // 初始化
      if (!Webrtc2Sip.isInited) {
        Webrtc2Sip.init(this.sessionEvent, this.stackEvent, {
          audioRemote: 'audio_remote',
        })
      }

      SDK.operatorquery()
        .then((res) => {
          const operator = res.eventdata
          // 获取启用的软终端
          webrtcList().then((res) => {
            const configs = res.data.eventdata
            configs.forEach((item) => {
              // if (
              //   item.enabled === 1 &&
              //   (item.phone === operator.mainTel ||
              //     item.phone === operator.viceTel)
              // ) {
              //   this.register(item)
              // }
              if (item.enabled === 1) {
                if (item.phone === operator.mainTel) {
                  item.phoneType = operator.mainTelType
                  this.register(item, 'main')
                } else if (item.phone === operator.viceTel) {
                  item.phoneType = operator.viceTelType
                  this.register(item, 'vice')
                }
              }
            })
          })
        })
        .catch((err) => {
          console.log('获取操作员信息失败')
        })
    },
    // 注册
    register(config, type) {
      if (!navigator.getUserMedia && !navigator.webkitGetUserMedia) {
        return this.$message({
          duration: 3000,
          type: 'error',
          message: '无法获取摄像头或麦克风',
        })
      }

      console.log('register')
      // 创建对象
      let webrtc2Sip = new Webrtc2Sip()
      // 注册
      webrtc2Sip.register(config)
      // 自定义事件
      // webrtc2Sip.setCustomEvent(this.sessionEvent, this.stackEvent);
      //定义到全局
      if (type == 'main') this.webrtc2Sip = webrtc2Sip
      else if (type == 'vice') this.webrtc2SipVice = webrtc2Sip
    },
    //摘挂机信号处理
    handleLocalAccept(msg) {
      console.log('信号上报')
      let path = this.$route.path
      console.log('path', path)
      if (path == '/phone') {
        window.handleLocalPhoneAccept(msg)
      } else {
        const deviceStatus = this.deviceStatusMap.get(this.operatorCallTels[0])
        if (
          deviceStatus != 'idle' &&
          deviceStatus != 'offline' &&
          deviceStatus != undefined
        ) {
          console.log('处理上报-接听状态', this.isAnswered)
          console.log('手柄状态', this.localPhoneStatus)
          console.log('按钮状态', this.localButtonStatus)
          if (this.isAnswered) {
            //挂断,话机放下并且扬声器按钮关闭状态
            if (
              this.localPhoneStatus == 'off' &&
              this.localButtonStatus == 'jyoff'
            ) {
              console.log('挂断')
              this.handlePlayDialt('pause')
              this.handleReject(this.webrtc2Sip, null)
            }
          } else {
            //话机拿起或按扬声器按钮->接听
            if (msg == 'on' || msg == 'jyon') {
              this.handlePlayDialt('pause')
              this.handleAccept(this.webrtc2Sip, null, false)
              //关闭来电显示
              this.notify.close()
            }
          }
        } else {
          if (this.localPhoneStatus == 'on') {
            this.handlePlayDialt('play')
          }
          if (
            this.localPhoneStatus == 'off' &&
            this.localButtonStatus == 'jyoff'
          ) {
            this.handlePlayDialt('pause')
          }
        }
      }
    },
    //摘机播放/停止回铃音
    handlePlayDialt(type) {
      //跳过集群页面
      // let path = this.$route.path
      // if (path == '/broadband') {
      //   return
      // }
      // const dialtone = document.getElementById('dialtone')
      // type == 'play' ? this.handleStartANew(dialtone) : dialtone.pause()
    },
    //重头播放
    handleStartANew(audio) {
      audio.currentTime = 0
      audio.play()
    },
  },
  mounted() {
    window['handleLocalAccept'] = (res) => {
      this.handleLocalAccept.call(this, res)
    }
    window['handlePlayDialt'] = (res) => {
      this.handlePlayDialt.call(this, res)
    }
    if (sessionStorage.getItem('tokenSign')) {
      //登录状态才能装载
      this.initWebrtc()
    }
  },
  created() {},
}
</script>
